import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  Task,
  CreateTaskRequest,
  UpdateTaskRequest,
  TaskLog,
  CreateTaskLogRequest
} from '@/types'
import {
  getTasks,
  createTask as createTaskApi,
  getTaskDetail,
  updateTask as updateTaskApi,
  deleteTask as deleteTaskApi,
  updateTaskGroup as updateTaskGroupApi,
  getMyDayTasks,
  getTaskLogs,
  createTaskLog as createTaskLogApi
} from '@/api'
import { useGroupStore } from './group'

// 任务状态管理
export const useTaskStore = defineStore('task', () => {
  // 状态 - 初始为空数组，通过API获取数据
  const tasks = ref<Task[]>([])
  const taskLogs = ref<TaskLog[]>([])
  const currentTask = ref<Task | null>(null)
  const isLoading = ref<boolean>(false)
  const currentPage = ref<number>(1)
  const pageSize = ref<number>(10)
  const total = ref<number>(0)
  const myDayTasks = ref<Task[]>([])

  // 获取分组store
  const groupStore = useGroupStore()

  // 计算属性
  const currentGroupTasks = computed(() => {
    return tasks.value.filter(task => task.group_id === groupStore.currentGroupId)
  })

  // 操作

  /**
   * 获取任务列表
   * @param params 查询参数
   */
  const fetchTasks = async (params?: {
    group_id?: number
    status?: number
    is_important?: boolean
    is_my_day?: boolean
    page?: number
    page_size?: number
  }) => {
    isLoading.value = true
    try {
      // 使用API获取数据
      const response = await getTasks({
        group_id: params?.group_id || groupStore.currentGroupId,
        status: params?.status,
        is_important: params?.is_important,
        is_my_day: params?.is_my_day,
        page: params?.page || currentPage.value,
        page_size: params?.page_size || pageSize.value
      })
      
      // 更新状态和任务数据
      tasks.value = response.items
      currentPage.value = params?.page || currentPage.value
      pageSize.value = params?.page_size || pageSize.value
      total.value = response.pagination.total
      
      return response
    } catch (error) {
      console.error('获取任务列表失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 创建任务
   * @param data 任务创建请求数据
   */
  const createTask = async (data: CreateTaskRequest) => {
    isLoading.value = true
    try {
      const response = await createTaskApi(data)
      tasks.value.push(response)
      return response
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 获取任务详情
   * @param id 任务ID
   */
  const fetchTaskDetail = async (id: number) => {
    isLoading.value = true
    try {
      const response = await getTaskDetail(id)
      currentTask.value = response
      return response
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 更新任务
   * @param id 任务ID
   * @param data 任务更新请求数据
   */
  const updateTask = async (id: number, data: UpdateTaskRequest) => {
    isLoading.value = true
    try {
      const response = await updateTaskApi(id, data)
      
      // 重新获取任务列表以保持数据同步
      await fetchTasks()
      
      // 重新获取"我的一天"任务列表
      await fetchMyDayTasks()
      
      return response
    } catch (error) {
      console.error('更新任务失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 删除任务
   * @param id 任务ID
   */
  const deleteTask = async (id: number) => {
    isLoading.value = true
    try {
      await deleteTaskApi(id)
      
      // 重新获取任务列表以保持数据同步
      await fetchTasks()
      
      // 重新获取"我的一天"任务列表
      await fetchMyDayTasks()
      
      // 清除当前任务（如果是当前任务）
      if (currentTask.value && currentTask.value.task_id === id) {
        currentTask.value = null
      }
      
      return { success: true }
    } catch (error) {
      console.error('删除任务失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 更新任务分组
   * @param id 任务ID
   * @param group_id 新的分组ID
   */
  const updateTaskGroup = async (id: number, group_id: number) => {
    isLoading.value = true
    try {
      await updateTaskGroupApi(id, group_id)
      // 更新本地任务列表
      const index = tasks.value.findIndex(task => task.task_id === id)
      if (index !== -1) {
        tasks.value[index].group_id = group_id
      }
      // 更新当前任务（如果是当前任务）
      if (currentTask.value && currentTask.value.task_id === id) {
        currentTask.value.group_id = group_id
      }
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 获取"我的一天"任务列表
   */
  const fetchMyDayTasks = async () => {
    isLoading.value = true
    try {
      // 使用API获取"我的一天"任务
      const response = await getMyDayTasks()
      myDayTasks.value = response.list
      return response
    } catch (error) {
      console.error('获取"我的一天"任务列表失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 获取任务日志列表
   * @param taskId 任务ID
   */
  const fetchTaskLogs = async (taskId: number) => {
    isLoading.value = true
    try {
      // 使用API获取任务日志
      const logs = await getTaskLogs(taskId)
      taskLogs.value = logs
      return logs
    } catch (error) {
      console.error('获取任务日志失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 添加任务日志
   * @param taskId 任务ID
   * @param data 日志创建请求数据
   */
  const createTaskLog = async (taskId: number, data: CreateTaskLogRequest) => {
    isLoading.value = true
    try {
      const log = await createTaskLogApi(taskId, data)
      taskLogs.value.push(log)
      return log
    } catch (error) {
      console.error('添加任务日志失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 清空当前任务
   */
  const clearCurrentTask = () => {
    currentTask.value = null
    taskLogs.value = []
  }

  return {
    tasks,
    myDayTasks,
    currentTask,
    taskLogs,
    isLoading,
    currentPage,
    pageSize,
    total,
    currentGroupTasks,
    fetchTasks,
    createTask,
    fetchTaskDetail,
    updateTask,
    deleteTask,
    updateTaskGroup,
    fetchMyDayTasks,
    fetchTaskLogs,
    createTaskLog,
    clearCurrentTask
  }
})
